package com.tsfyun.scm.config.declare;

import com.alibaba.fastjson.JSONObject;
import com.rabbitmq.client.Channel;
import com.tsfyun.common.base.config.properties.NoticeProperties;
import com.tsfyun.common.base.dto.DeclareBizReceiveDTO;
import com.tsfyun.common.base.help.DingTalkNoticeUtil;
import com.tsfyun.scm.service.customs.IDeclarationReceiptService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.io.IOException;

@Slf4j
@Component
public class DeclareNoticeReceiver {

    @Autowired
    private NoticeProperties noticeProperties;
    @Autowired
    private IDeclarationReceiptService declarationReceiptService;

    @RabbitListener(queues = "scm_declare_receipt")
    public void declareNoticeReceiver(Channel channel, Message message) throws IOException {
        String messageContent = new String(message.getBody());
        String msgId = message.getMessageProperties().getCorrelationId();
        log.info("监听到消息唯一id:【{}】，消息内容：【{}】",msgId,messageContent);
        DeclareBizReceiveDTO dto = JSONObject.parseObject(messageContent, DeclareBizReceiveDTO.class);
        try {
            //回执处理
            declarationReceiptService.receive(dto);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
            log.info("消息id：【{}】，消息内容：【{}】，消息消费成功",msgId,messageContent);
        }catch (Exception e) {
            //丢弃消息
            channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, false);
            log.error(String.format("消息id：【%s】，消息内容：【%s】，消息消费失败",msgId,messageContent),e);
            //告知平台
            DingTalkNoticeUtil.send2DingDingOtherException("报关渠道》MQ消息消费失败",messageContent,e,noticeProperties.getDingdingUrl());
            log.info("消息id：【{}】，消息内容：【{}】，消息消费失败",msgId,messageContent);
        }finally {

        }
    }
}
